package log

import (
	"os"
	"time"

	rotatelogs "github.com/lestrrat-go/file-rotatelogs"
	"github.com/natefinch/lumberjack"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
)

var SugarLogger *zap.SugaredLogger
var Logger *zap.Logger

func InitLogger() {

	encoder := getEncoder()
	// 控制台日志
	consoleDebugging := zapcore.Lock(os.Stdout)
	var allCore []zapcore.Core
	consolecore := zapcore.NewCore(encoder, consoleDebugging, zapcore.DebugLevel)
	allCore = append(allCore, consolecore)
	// 文件日志
	writeSyncer := getWriterRotate("logfile/test")
	filecore := zapcore.NewCore(encoder, writeSyncer, zapcore.DebugLevel)
	allCore = append(allCore, filecore)
	core := zapcore.NewTee(allCore...)
	logger := zap.New(core, zap.AddCaller(), zap.AddStacktrace(zapcore.ErrorLevel))
	SugarLogger = logger.Sugar()
	Logger = SugarLogger.Desugar()
	zap.ReplaceGlobals(Logger)
	defer SugarLogger.Sync()
}

func getEncoder() zapcore.Encoder {
	encoderConfig := zap.NewProductionEncoderConfig()
	encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
	encoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder
	return zapcore.NewConsoleEncoder(encoderConfig)
}

func getLogWriter() zapcore.WriteSyncer {
	lumberJackLogger := &lumberjack.Logger{
		Filename:   "./test.log",
		MaxSize:    1,
		MaxBackups: 5,
		MaxAge:     30,
		Compress:   false,
	}
	return zapcore.AddSync(lumberJackLogger)
}

func getWriterRotate(filename string) zapcore.WriteSyncer {
	// 生成rotatelogs的Logger 实际生成的文件名 demo.log.YYmmddHH
	// demo.log是指向最新日志的链接
	// 保存7天内的日志，每天分割一次日志
	hook, err := rotatelogs.New(
		filename+".%Y-%m-%d.log", // 没有使用go风格反人类的format格式
		rotatelogs.WithLinkName(filename),
		rotatelogs.WithMaxAge(time.Hour*24*7),
		rotatelogs.WithRotationTime(24*time.Hour),
	)

	if err != nil {
		panic(err)
	}
	return zapcore.AddSync(hook)

}
